﻿using System;
using System.Collections.Generic;
using System.DirectoryServices.Protocols;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Simple.Services.System.QHSEDanger.Models.AnalysisInput;
using Simple.Services.System.QHSEViolationCategory.Models;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

public class AnalysisPageService
{
    private readonly SimpleDbContext _context;
    private readonly CacheService _cacheService;
    private readonly QHSEXyViolationTypeService _violationTypeService;
    private readonly QHSEKeyWorkSpecialtyService _keyWorkSpecialtyService;
    private readonly QHSEOrganizationService _organizationService;
    private readonly QHSEDictionaryService _dictionaryService;
    public AnalysisPageService(SimpleDbContext context, QHSEXyViolationTypeService violationTypeService, QHSEDictionaryService dictionaryService, QHSEKeyWorkSpecialtyService keyWorkSpecialtyService,QHSEOrganizationService organizationService, CacheService cacheService)
    {
        _context = context;
        _violationTypeService = violationTypeService;
        _dictionaryService = dictionaryService;
        _keyWorkSpecialtyService = keyWorkSpecialtyService;
        _organizationService = organizationService;
        _cacheService = cacheService;
    }
    private static string EscapeLikePattern(string pattern)
    {
        return pattern.Replace("'", "''").Replace("/", "//").Replace("_", "/_").Replace("%", "/%");
    }
    public async Task<QHSEVadTotalResultModel> QHSEVadTotalAnalysisAsync()
    {
        var cacheResult = await _cacheService.GetPageAnalysisTotalAsync();
        if (cacheResult != null)
        {
            return cacheResult;
        }
        var dateOn = new DateTime(DateTime.Now.Year, 1, 1);
        var dateEnd = DateTime.Now;
        var vquery = _context.Set<QHSESysXyViolation>().AsNoTracking().Select(u=>u.CheckDate).AsQueryable();
        var dquery = _context.Set<QHSESysDanger>().AsNoTracking().Select(u => u.CheckDate).AsQueryable();

        List<Task<int>> vTasks = new List<Task<int>>();
        List<Task<int>> dTasks = new List<Task<int>>();

        for (int i = 1; i <= DateTime.Now.Month; i++)
        {
            DateTime startDate = dateOn.AddMonths(i - 1);
            DateTime endDate = dateOn.AddMonths(i);

            vTasks.Add(vquery.Where(u => u >= startDate && u <= endDate).CountAsync());
            dTasks.Add(dquery.Where(u => u >= startDate && u <= endDate).CountAsync());
        }

        var vResults = await Task.WhenAll(vTasks);
        var dResults = await Task.WhenAll(dTasks);

        List<ViolationAnalysisResult> vTrend = Enumerable.Range(0, DateTime.Now.Month)
            .Select(i => new ViolationAnalysisResult
            {
                Name = new DateTime(DateTime.Now.Year, i + 1, 1).ToString("MMMM", new CultureInfo("zh-CN")),
                Value = vResults[i]
            }).ToList();

        List<DangerAnalysisResult> dTrend = Enumerable.Range(0, DateTime.Now.Month)
            .Select(i => new DangerAnalysisResult
            {
                Name = new DateTime(DateTime.Now.Year, i + 1, 1).ToString("MMMM", new CultureInfo("zh-CN")),
                Value = dResults[i]
            }).ToList();

        int vTotal = vResults.Sum();
        int dTotal = dResults.Sum();

        var result = new QHSEVadTotalResultModel
        {
            ViolationTotal = vTotal,
            DangerTotal = dTotal,
            violationTrend = vTrend,
            dangerTrend = dTrend
        };
        await _cacheService.SetPageAnalysisTotalAsync(result);
        return result;
    }

    public async Task<List<ViolationAnalysisResult>> QHSEViolationTypeAnalysisAsync()
    {
        var cacheResult = await _cacheService.GetPageAnalysisVTypeAsync();
        if (cacheResult != null)
        {
            return cacheResult;
        }
        var dateOn = new DateTime(DateTime.Now.Year, 1, 1);
        var dateEnd = DateTime.Now;
        List<ViolationAnalysisResult> result = new List<ViolationAnalysisResult>();
        var query = _context.Set<QHSESysXyViolation>().AsNoTracking().Where(u => u.CheckDate >= dateOn && u.CheckDate <= dateEnd).Select(u=>u.ViolationType).AsQueryable();
        var violationTypes = await _violationTypeService.GetAsync();

        if (violationTypes != null)
        {
            var violationTypeItems = violationTypes.Select(d => d.ViolationType).ToList();

            // 循环填充结果列表
            foreach (var violationTypeItem in violationTypeItems)
            {
                var count = query.Count(d => d == violationTypeItem);
                result.Add(new ViolationAnalysisResult { Name = violationTypeItem, Value = count });
            }
        }

        // 按值排序
        result = result.OrderByDescending(u => u.Value).ToList();
        await _cacheService.SetPageAnalysisVTypeAsync(result);
        return result;
    }


    public async Task<List<DangerAnalysisResult>> QHSEDangerTypeAnalysisAsync()
    {
        var cacheResult = await _cacheService.GetPageAnalysisDTypeAsync();
        if (cacheResult != null)
        {
            return cacheResult;
        }
        var dateOn = new DateTime(DateTime.Now.Year, 1, 1);
        var dateEnd = DateTime.Now;
        List<DangerAnalysisResult> result = new List<DangerAnalysisResult>();
        var query = _context.Set<QHSESysDanger>().AsNoTracking().Where(u => u.CheckDate >= dateOn && u.CheckDate <= dateEnd).Select(u=>u.DangerType).AsQueryable();
        var dangerTypes = await _dictionaryService.GetDictionaryAsync("1010");

        if (dangerTypes != null)
        {
            var dangerTypeItems = dangerTypes.Select(d => d.Item).ToList();

            // 循环填充结果列表
            foreach (var dangerTypeItem in dangerTypeItems)
            {
                var count = query.Count(d => d == dangerTypeItem);
                result.Add(new DangerAnalysisResult { Name = dangerTypeItem, Value = count });
            }
        }

        // 按值排序
        result = result.OrderByDescending(u => u.Value).ToList();
        await _cacheService.SetPageAnalysisDTypeAsync(result);
        return result;
    }

    public async Task<List<ViolationAnalysisResult>> QHSEViolationWorkSpecialtyAnalysisAsync()
    {
        var cacheResult = await _cacheService.GetPageAnalysisVSpecialtyAsync();
        if (cacheResult != null)
        {
            return cacheResult;
        }
        List<ViolationAnalysisResult> result = new List<ViolationAnalysisResult>();
        var dateOn = new DateTime(DateTime.Now.Year, 1, 1);
        var dateEnd = DateTime.Now;
        var query = _context.Set<QHSESysXyViolation>().AsNoTracking().Where(u => u.CheckDate >= dateOn && u.CheckDate <= dateEnd).Select(u=>u.WorkSpecialty).AsQueryable();
        List<QHSEKeyWorkSpecialtyModel> workSpecialty = await _keyWorkSpecialtyService.GetAsync();
        if (workSpecialty != null)
        {
            var specialties = workSpecialty.Select(s => s.Specialty).ToList();

            // 创建包含所有工种专业的列表
            var allSpecialties = new HashSet<string>(specialties);

            // 统计违规记录
            var violationCounts = query
                .GroupBy(d => d)
                .Select(g => new { Specialty = g.Key, Count = g.Count() })
                .ToDictionary(x => x.Specialty, x => x.Count);

            // 遍历所有工种专业，将违规次数添加到结果列表中
            foreach (var specialty in allSpecialties)
            {
                var count = violationCounts.ContainsKey(specialty) ? violationCounts[specialty] : 0;
                result.Add(new ViolationAnalysisResult { Name = specialty, Value = count });
            }
        }

        result = result.OrderByDescending(u => u.Value).ToList();
        await _cacheService.SetPageAnalysisVSpecialtyAsync(result);
        return result;
    }
    public async Task<List<DangerAnalysisResult>> QHSEDangerWorkSpecialtyAnalysisAsync()
    {
        var cacheResult = await _cacheService.GetPageAnalysisDSpecialtyAsync();
        if (cacheResult != null)
        {
            return cacheResult;
        }
        List<DangerAnalysisResult> result = new List<DangerAnalysisResult>();
        var dateOn = new DateTime(DateTime.Now.Year, 1, 1);
        var dateEnd = DateTime.Now;
        var query = _context.Set<QHSESysDanger>()
                            .AsNoTracking()
                            .Where(u => u.CheckDate >= dateOn && u.CheckDate <= dateEnd)
                            .Select(u=>u.WorkSpecialty)
                            .AsQueryable();
        List<QHSEKeyWorkSpecialtyModel> workSpecialty = await _keyWorkSpecialtyService.GetAsync();

        if (workSpecialty != null)
        {
            var specialties = workSpecialty.Select(s => s.Specialty).ToList();

            // 创建包含所有工种专业的列表
            var allSpecialties = new HashSet<string>(specialties);

            // 统计违规记录
            var violationCounts = query
                .GroupBy(d => d)
                .Select(g => new { Specialty = g.Key, Count = g.Count() })
                .ToDictionary(x => x.Specialty, x => x.Count);

            // 遍历所有工种专业，将违规次数添加到结果列表中
            foreach (var specialty in allSpecialties)
            {
                var count = violationCounts.ContainsKey(specialty) ? violationCounts[specialty] : 0;
                result.Add(new DangerAnalysisResult { Name = specialty, Value = count });
            }
        }

        result = result.OrderByDescending(u => u.Value).ToList();
        await _cacheService.SetPageAnalysisDSpecialtyAsync(result);
        return result;
    }

    public async Task<List<ViolationAnalysisResult>> QHSEViolationSecondaryUnitAnalysisAsync()
    {
        var cacheResult = await _cacheService.GetPageAnalysisVSecondaryAsync();
        if (cacheResult != null)
        {
            return cacheResult;
        }
        var dateOn = new DateTime(DateTime.Now.Year, 1, 1);
        var dateEnd = DateTime.Now;
        List<ViolationAnalysisResult> result = new List<ViolationAnalysisResult>();
        // 获取所有二级单位的名称
        var query = _context.Set<QHSESysXyViolation>().AsNoTracking().Where(u =>u.CheckDate >= dateOn && u.CheckDate <= dateEnd).AsQueryable();
        var newQuery =await query
                        .Join(_context.Set<QHSESysOrganization>(), // Join with QHSEOrganization table
                            joinResult => joinResult.CheckOrganizationId,
                            organization => organization.OrganizationId,
                            (joinResult, organization) => new { Danger = joinResult, Organization = organization })
                        .Select(u => u.Organization.NamePath).ToListAsync();
        List<QHSESysOrganization> orgs = await _organizationService.GetSon("00");
        if (orgs != null)
        {
            foreach (var org in orgs)
            {
                var value = newQuery.Where(joinResult => joinResult.Contains(org.NamePath)).Count();
                ViolationAnalysisResult res = new ViolationAnalysisResult();
                res.Name = org.OrganizationName;
                res.Value = value;
                result.Add(res);
            }
        }
        result = result.OrderByDescending(u => u.Value).ToList();
        await _cacheService.SetPageAnalysisVSecondaryAsync(result);
        return result;
    }
    public async Task<List<DangerAnalysisResult>> QHSEDangerSecondaryUnitAnalysisAsync()
    {
        var cacheResult = await _cacheService.GetPageAnalysisDSecondaryAsync();
        if (cacheResult != null)
        {
            return cacheResult;
        }
        var dateOn = new DateTime(DateTime.Now.Year, 1, 1);
        var dateEnd = DateTime.Now;
        List<DangerAnalysisResult> result = new List<DangerAnalysisResult>();
        // 获取所有二级单位的名称
        var query = _context.Set<QHSESysDanger>().AsNoTracking().Where(u => u.CheckDate >= dateOn && u.CheckDate <= dateEnd).AsQueryable();
        var newQuery= query
                        .Join(_context.Set<QHSESysOrganization>(), // Join with QHSEOrganization table
                            joinResult => joinResult.CheckOrganizationId,
                            organization => organization.OrganizationId,
                            (joinResult, organization) => new { Danger = joinResult, Organization = organization })
                        .Select(u => u.Organization.NamePath);
        List<QHSESysOrganization> orgs = await _organizationService.GetSon("00");
        if (orgs != null)
        {
            foreach (var org in orgs)
            {
                var value =newQuery.Where(joinResult => joinResult.Contains(org.NamePath)).Count();
                DangerAnalysisResult res = new DangerAnalysisResult();
                res.Name = org.OrganizationName;
                res.Value = value;
                result.Add(res);
            }
        }
        result = result.OrderByDescending(u => u.Value).ToList();
        await _cacheService.SetPageAnalysisDSecondaryAsync(result);
        return result;
    }

}
